package xpn.platform.modules.sys.user;

import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.rest.core.annotation.HandleBeforeCreate;
import org.springframework.data.rest.core.annotation.HandleBeforeSave;
import org.springframework.data.rest.core.annotation.RepositoryEventHandler;
import xpn.platform.common.config.XpnPlatformConfig;
import xpn.platform.common.exception.XpnBusinessException;
import xpn.platform.common.exception.XpnExceptionCodeEnum;
import xpn.platform.common.util.Tool;

/**
 * 系统用户 实体  事件监听
 *
 * @author duwei
 * @version 2017/11/13 18:26
 */
@RepositoryEventHandler(SysUser.class)
public class SysUserEventHandler {

    @Autowired
    XpnPlatformConfig xpnPlatformConfig;

    @HandleBeforeCreate
    public void beforeCreate(SysUser sysUser) {
        String passwordDigest = xpnPlatformConfig.getSecurity().getPasswordDigest();
        if (!Strings.isNullOrEmpty(passwordDigest) && !"none".equals(passwordDigest.toLowerCase())) {
            String password = sysUser.getRealPassword();
            sysUser.setPassword(Tool.MD5(password));
        }
    }

    @HandleBeforeSave
    public void beforeSave(SysUser sysUser) {
        String passwordDigest = xpnPlatformConfig.getSecurity().getPasswordDigest();
        if (!Strings.isNullOrEmpty(passwordDigest) && !"none".equals(passwordDigest.toLowerCase())) {
            String password = sysUser.getRealPassword();
            if (!Strings.isNullOrEmpty(password)) {
               if(Tool.validPwd(password)){
                   sysUser.setPassword(Tool.MD5(password));
                }else{
                    throw new XpnBusinessException(XpnExceptionCodeEnum.PASSWORD_FALED);
                }
            }
        }
    }
}
